﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.Apilication.Common;
using Traceability.App.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure.Interfance;

namespace Traceability.App.Apilication.Handler
{
    public class DelTraceabilityHandler : IRequestHandler<DelTraceabilityCommon, ApiResult<int>>
    {
        private readonly IBaseRespository<TraceabilityModel> traceabilityRepo;
        private readonly IMapper mapper;

        public DelTraceabilityHandler(IBaseRespository<TraceabilityModel> traceabilityRepo,IMapper mapper)
        {
            this.traceabilityRepo = traceabilityRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelTraceabilityCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            //var trace = traceabilityRepo.GetAll().Where(x=>x.Product_Name==request.Product_Name).FirstOrDefault();
            //if (trace != null)
            //{
            //    res.Code=ApiEnum.Error;
            //    res.Message = "商品名称已存在";
            //    return Task.FromResult(res);
            //}
            var info = traceabilityRepo.GetValue(request.Traceability_ID).Result;
            
           info.Delete_Identifier=true;
            var r = 0;
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r= traceabilityRepo.Update(info).Result;
                tran.Complete();
            }
            if(r>0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "删除成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "删除失败";
                return Task.FromResult(res);
            }
        }
    }
}
